package top.milkbox.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.milkbox.domain.Userinfo;
import top.milkbox.service.UserinfoService;
import top.milkbox.utils.R;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/userinfos")
public class UserinfoController {

    @Autowired
    private UserinfoService userinfoService;

    @PostMapping("/login")
    public R login(@RequestBody String code, HttpSession session) {
        HttpSession responseSession = userinfoService.login(code, session);
        R r = new R();
        if (responseSession != null) {
            r.setFlag(true);
            r.setData(responseSession.getAttribute("userinfo"));
            r.setSessionId(responseSession.getId());
            r.setMessage("登录成功");
        } else {
            r.setFlag(false);
            r.setMessage("登录失败，用户不存在");
        }
        return r;
    }

    @PostMapping("/register")
    public R register(
            @RequestParam String code,
            @RequestBody Userinfo userinfo) {
        System.out.println("------> code: " + code);
        System.out.println("------> userinfo: " + userinfo.toString());
        if (userinfoService.register(code, userinfo)) {
            return new R(true, "注册成功");
        } else {
            return new R(false, "注册失败，用户已存在");
        }
    }

    /**
     * 登出
     */
    @GetMapping("/logout")
    public R logout(HttpSession session) {
        Boolean isLogoutSuccess = userinfoService.logout(session);
        if (isLogoutSuccess) {
            return new R(true, "登出成功");
        } else {
            return new R(false, "登出失败，session不存在或已经销毁");
        }
    }

}
